<template>
  <div>
    <!--左边-->
    <!--一级菜单-->
    <div class="leftMenu left-menu">
      <div class="left-menu-btn">
        <a-icon type="up" :disabled="downBtn" @click="handleMenuMove('down')" />
      </div>
      <ul ref="menuList" class="left-menu-list" @mousedown="menuDrag" @wheel="menuWheel">
        <div ref="cursor" class="left-menu-list-cursor" />
        <template v-for="{ id, raw: { name, code } } in menus">
          <li v-if="filterMenuIcon(code) !== ''" :key="id" :class="{ 'left-menu-item-active': menuActive === id }"
            @click="handleChange($event, id)">
            <a-badge :count="messageCount[code]" :number-style="{ backgroundColor: '#F59A23' }">
              <img :src="filterMenuIcon(code)" />
              <p>{{ name }}</p>
            </a-badge>
          </li>
        </template>
      </ul>
      <div class="left-menu-btn">
        <a-icon type="down" :disabled="upBtn" @click="handleMenuMove('up')" />
      </div>
    </div>

    <!--二级菜单-->
    <div class="menuLists" :style="{ left: showSecondaryMenu ? '80px' : '-120px' }">
      <div>
        <!-- <div class="logoName">
          <img style="margin-right: 5px; width: 40px" src="../../src/assets/logo.png" />
          <div style="width: 100px; height: 40px; font-size: 14px; display: flex; flex-direction: column; align-items: center">
            <div>{{ title1 }}</div>
            <div>{{ title2 }}</div>
          </div>
        </div> -->
        <div>
          <div class="menuList">
            <div v-for="item in menuList" :key="item.id">
              <div>
                <a-menu mode="inline" :selected-keys="activePath" :style="{ height: '100%', borderRight: 0 }"
                  :open-keys="newOpenKeys" class="menu" @openChange="handelMenuOpenChange">
                  <a-sub-menu v-if="item.raw.style != 'hidden'" :key="item.id">
                    <span slot="title">
                      <a-icon type="home" />
                      <a-badge :count="badgeShow(item) ? messageCount[item.raw.code] : 0"
                        :number-style="{ backgroundColor: '#F59A23' }" :offset="[6, -2]">
                        <ellipsis :length="15" tooltip placement="right">{{ item.raw.name }}</ellipsis>
                      </a-badge>
                    </span>
                    <template v-for="items in item.children">
                      <!-- <a-menu-item 
                        v-if="items.raw.style != 'hidden'"
                        :key="items.raw.value"
                        @click="handleLink(items.raw.value)"
                      >
                        <a-badge
                          :count="messageCount[items.raw.code]"
                          :number-style="{ backgroundColor: '#F59A23' }"
                          :offset="[6, -2]"
                        >
                         
                          <ellipsis :length="18" tooltip placement="right">
                            {{ items.raw.name }}
                          </ellipsis>
                        </a-badge>
                      </a-menu-item> -->
                      <template v-if="items.raw.style != 'hidden'">
                        <a-menu-item v-if="!items.children.length" :key="items.raw.value"
                          @click="handleLink(items.raw.value)">
                          <a-badge :count="messageCount[items.raw.code]" :number-style="{ backgroundColor: '#F59A23' }"
                            :offset="[6, -2]">
                            <ellipsis :length="18" tooltip placement="right">
                              {{ items.raw.name }}
                            </ellipsis>
                          </a-badge>
                        </a-menu-item>
                        <a-sub-menu v-else :key="items.id" :title="items.raw.name">
                          <template v-for="four in items.children">
                            <!-- <a-menu-item class="four-menu"  @click="handleLink(four.raw.value)" :key="four.raw.value" :title="four.raw.name">{{ four.raw.name }} </a-menu-item> -->
                            <a-menu-item class="four-menu" :key="four.raw.value" @click="handleLink(four.raw.value)">
                              <a-badge :count="messageCount[four.raw.code]"
                                :number-style="{ backgroundColor: '#F59A23' }" :offset="[6, -2]">
                                <ellipsis :length="18" tooltip placement="right">
                                  {{ four.raw.name }}
                                </ellipsis>
                              </a-badge>
                            </a-menu-item>
                          </template>
                        </a-sub-menu>
                      </template>
                    </template>
                  </a-sub-menu>
                </a-menu>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="left-layer-retract-btn base-btn" :style="{
      ...retractStyle,
      left: showSecondaryMenu ? '280px' : '80px'
    }" @click="handleSecondaryMenu">
      <a-icon v-if="!showSecondaryMenu" type="caret-right" />
      <a-icon v-else type="caret-left" />
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { mapState } from 'vuex'
import FooterToolBar from '@/components/FooterToolbar'
import ASubMenu from 'ant-design-vue/es/menu/SubMenu'
import { Ellipsis } from '@/components'
import setting from '@/config/defaultSettings'
import { getMenuIcon } from '@/utils/util.js'

export default {
  name: 'MenuBasic',
  components: {
    ASubMenu,
    // FooterToolBar,
    Ellipsis
  },
  computed: {
    ...mapState({
      // 动态主路由
      mainMenu: (state) => state.permission.addRouters,
      menus: (state) => state.user.menus
    }),
    toDoCount() {
      let count = Number(this.$store.getters['messageInfo/GET_TODOCOUNT'])
      return isNaN(count) ? 0 : count
    },
    doneCount() {
      let count = Number(this.$store.getters['messageInfo/GET_DONECOUNT'])
      return isNaN(count) ? 0 : count
    },
    toReadCount() {
      let count = Number(this.$store.getters['messageInfo/GET_TOREADCOUNT'])
      return isNaN(count) ? 0 : count
    },
    toReadPostsChangeLog() {
      let count = Number(this.$store.getters['messageInfo/GET_TOREADPOSTSCHANGELOGCOUNT'])
      return isNaN(count) ? 0 : count
    },
    toNewsCount() {
      let count = Number(this.$store.getters['messageInfo/GET_TONEWSCOUNT'])
      return isNaN(count) ? 0 : count
    },
    messageCount() {
      const counts = {
        thi: this.toDoCount + this.toReadCount + this.doneCount,
        thi_001: this.toDoCount + this.doneCount,
        thi_001_dbsx: this.toDoCount,
        thi_002: this.toReadCount,
        thi_002_ddxx: this.toReadCount,
        thi_001_wfqd: this.doneCount,
        SYSMG: this.toReadPostsChangeLog, //菜单：系统
        sy_xtyhgl: this.toReadPostsChangeLog, //菜单：系统-系统用户管理
        sy_009: this.toReadPostsChangeLog, //菜单：系统-岗位变更日志
        pa_016: this.toNewsCount //菜单：新闻
      }
      return counts
    },
    activePath() {
      let path = this.$route.path
      // pathMap储存着当前路由页面的来源，键为当前路由的fullPath,值为来源的fullPath
      const pathMap = this.$store.getters['tabInfo/GET_PATHMAP']
      // console.log(pathMap)
      // if(pathMap) {
      //   const { noTab } = this.$route.meta
      //   const { fullPath } = this.$route
      //   path = noTab && pathMap[fullPath] || path
      // }
      if (pathMap) {
        const { fullPath } = this.$route
        let res = pathMap.find((v) => v.fullPath === fullPath)
        if (res) {
          path = res.path
        }
      }
      return [path]
    }
  },
  data() {
    return {
      newOpenKeys: [], // 打开的菜单
      title1: setting.title1, // 标题
      title2: setting.title2, // 标题
      showSecondaryMenu: true,
      count: 0,
      menuList: [],
      menuActive: '', // 当前tab
      thirdMenu: false, // 三级菜单
      dataList: [], // 单级所有菜单
      status: 'all',
      retractStyle: {
        cursor: 'pointer',
        background: `url("") center center no-repeat`
      },
      // 菜单按钮禁用状态
      upBtn: false,
      downBtn: false,
      badgeMenus: new Set(['thi_001_dbsx', 'thi_002_ddxx', 'thi_001_wfqd', 'sy_009', 'pa_016']),
      badgeShow: (e) => {
        const b = new Set(e.children.map((i) => i.raw.code))
        const intersect = new Set([...this.badgeMenus].filter((x) => b.has(x)));
        return Array.from(intersect)?.length !== 0
      }
    }
  },
  mounted() {
    let menus0 = []
    // 把多级菜单生成单级全部列表
    this.generateList(this.menus)
    if (this.activePath == this.$router.options.routes[0].path) {
      let okMenus = this.menus.filter((v) => this.filterMenuIcon(v.raw.code) !== '')
      // menus0 = this.menus[0]
      // this.menuActive = this.menus[0].id
      menus0 = okMenus[0]
      this.menuActive = okMenus[0].id
    } else {
      // 初始化菜单
      this.initMenu()
      menus0 = this.menus.find((item) => item.id == this.menuActive)
    }
    if (menus0 && Object.keys(menus0).length > 0) {
      this.menuList = menus0.children
    } else {
      this.menuList = []
    }
    this.getTwoMenu(menus0)
  },
  watch: {
    activePath(val) {
      // console.log(val)
      let menus0 = []
      this.initMenu()
      menus0 = this.menus.find((item) => item.id == this.menuActive)
      if (menus0 && Object.keys(menus0).length > 0) {
        this.menuList = menus0.children
      } else {
        this.menuList = []
      }
      this.getTwoMenu(menus0)
    }
  },
  methods: {
    /**
     * 更新打开菜单
     */
    updateOpenKeys() {
      if (this.activePath == '/index') {
        this.newOpenKeys = []
        return
      }
      const targetMenu = this.dataList.find((item) => item.value == this.activePath)
      if (targetMenu) {
        this.newOpenKeys = [targetMenu.parentId]
        const parentId = this.dataList.find((item) => item.id == targetMenu.parentId)?.parentId
        parentId && this.newOpenKeys.push(parentId)
      }
    },
    /**
     * 保持最多打开一个二级菜单项
     */
    handelMenuOpenChange(openKeys) {
      console.log(openKeys, 'openKeys')
      this.newOpenKeys = openKeys
      // console.log(this.newOpenKeys,'22222222',[openKeys[openKeys.length - 1]],2)
      // this.newOpenKeys = openKeys.length ? [openKeys[openKeys.length - 1]] : []
    },
    /**
     * 处理菜单图标异常
     * @param {Object} data 菜单对象
     */
    filterMenuIcon(code) {
      return getMenuIcon(code)
    },
    handleSecondaryMenu() {
      this.showSecondaryMenu = !this.showSecondaryMenu
      this.$emit('switchSecondaryMenu', this.showSecondaryMenu)
    },
    handleLink(path) {
      // 跳转到系统外的路径
      const outMap = {
        '/cscec8b': 'https://app.cscec8b.com.cn/portalwebii/index.html#/login',
        '/humanResources/home': 'https://hr.cscecxn.com/api/auth/login_by_sso?sso=customer_sso&next=/%23/index&token=' + Vue.getAcloudProvider().getAccessToken() // 人力资源
      }
      const outPath = path.split('-')?.[0] || ''
      if (outMap[outPath]) {
        window.open(outMap[outPath], '_blank')
        return
      }
      this.$router.push({
        path: outMap[outPath] ? outPath : path
      })
    },
    // 切换tab菜单
    handleChange(e, id) {
      this.menuActive = id
      const menuItem = this.menus.filter((item) => item.id == id)[0]
      this.getTwoMenu(menuItem)
      this.cursorChange(e)
    },
    /**
     * @description: 菜单光标
     * @param {Void}
     * @return {Void}
     */
    cursorChange(e) {
      this.$refs.cursor.style.top = e.currentTarget.offsetTop + 'px'
    },
    /**
     * @description: 菜单拖拽
     * @param {Void}
     * @return {Void}
     */
    menuDrag(e) {
      const list = e.currentTarget
      let lastY = list.scrollTop
      let y = e.clientY
      document.onmousemove = (ev) => {
        const h = document.body.clientHeight
        const w = document.body.clientWidth
        // 判断是否在浏览器可视区域
        if (h - ev.clientY > 0 && h - ev.clientY < h && w - ev.clientX > 0 && w - ev.clientX < w) {
          const menuList = this.$refs.menuList
          let scrollTop = menuList.scrollTop
          let clientHeight = menuList.clientHeight
          let scrollHeight = menuList.scrollHeight
          list.scrollTop = lastY + (y - ev.clientY)
          if (scrollTop > 0) {
            this.downBtn = false
            if (scrollTop + clientHeight >= scrollHeight) {
              this.upBtn = true
            } else {
              this.upBtn = false
            }
          } else {
            this.downBtn = true
          }
        } else {
          document.onmousemove = null
        }
      }
      document.onmouseup = () => {
        document.onmousemove = document.onmouseup = null
      }
    },
    /**
     * @description: 菜单鼠标滚动监听
     * @param {Void}
     * @return {Void}
     */
    menuWheel() {
      const menuList = this.$refs.menuList
      let scrollTop = menuList.scrollTop
      let clientHeight = menuList.clientHeight
      let scrollHeight = menuList.scrollHeight
      if (scrollTop > 0) {
        this.downBtn = false
        if (scrollTop + clientHeight >= scrollHeight) {
          this.upBtn = true
        } else {
          this.upBtn = false
        }
      } else {
        this.downBtn = true
      }
    },
    /**
     * @description: 菜单移动
     * @param {String} type 移动类型
     * @return {*}
     */
    handleMenuMove(type) {
      const menuList = this.$refs.menuList
      let clientHeight = menuList.clientHeight
      let scrollHeight = menuList.scrollHeight
      if (type === 'up') {
        let timer = null
        let index = 0
        const fun = () => {
          timer = setTimeout(() => {
            let scrollTop = menuList.scrollTop
            if (scrollTop + clientHeight < scrollHeight && index < 100) {
              menuList.scrollTop = menuList.scrollTop + 4
              index++
              this.downBtn = false
              fun()
            } else {
              this.upBtn = true
              clearTimeout(timer)
              timer = null
            }
          }, 4)
        }
        fun()
      }
      if (type === 'down') {
        let timer = null
        let index = 0
        const fun = () => {
          timer = setTimeout(() => {
            let scrollTop = menuList.scrollTop
            if (scrollTop > 0 && index < 100) {
              menuList.scrollTop = menuList.scrollTop - 4
              index++
              this.upBtn = false
              fun()
            } else {
              this.downBtn = true
              clearTimeout(timer)
              timer = null
            }
          }, 4)
        }
        fun()
      }
    },
    // 把多级菜单生成单级全部列表
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        const id = node.id
        this.dataList.push({ id, parentId: node.parentId, value: node.raw.value, name: node.raw.name })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    // 初始化菜单
    initMenu() {
      this.updateOpenKeys()
      let list = this.dataList.filter((i) => i.value == this.activePath)
      if (list.length > 0) {
        this.getParent(list[0].parentId, list[0].id)
      } else {
        return
      }
    },
    // 获取父级节点
    getParent(id, preId) {
      // 筛选出节点
      let parentNode = this.dataList.filter((i) => i.id == id)
      // 有父级
      if (parentNode.length > 0) {
        // 再次获取父级
        this.getParent(parentNode[0].parentId, parentNode[0].id)
        // 无父级
      } else {
        // 映射顶级菜单id
        this.menuActive = preId
      }
    },
    getTwoMenu(item) {
      if (!item) {
        return
      }
      let _this = this
      let arr = item.children
      if (arr[0] != undefined) {
        if (item.children.length > 0) {
          _this.menuList = item.children
          _this.thirdMenu = true
        } else {
          _this.thirdMenu = false
        }
      } else {
        let arrys = []
        arrys.push(item)
        _this.menuList = arrys
      }
    }
  }
}
</script>

<style lang="less">
.slide-fade-enter-active {
  transition: all 0.5s ease;
}

.slide-fade-leave-active {
  transition: all 0.5s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter,
.slide-fade-leave-to

/* .slide-fade-leave-active for below version 2.1.8 */
  {
  transform: translateX(10px);
  opacity: 0;
}
</style>

<style lang="less" scoped="scoped">
@import './BasicLayout.less';

/deep/ .ant-tabs-left-bar {
  border-right: none !important;

  .ant-tabs-nav {
    .ant-tabs-tab {
      opacity: 0.6;
      color: #ffffff;
    }

    .ant-tabs-tab-active,
    .ant-tabs-tab-active:hover {
      opacity: 1;
      color: #fff;
    }

    .ant-tabs-ink-bar {
      background: #fff;
      right: initial !important;
      width: 3px !important;
    }
  }
}

/deep/ .three-menu {
  padding-left: 40px !important;
}

/deep/ .four-menu {
  padding-left: 56px !important;
}

.thirds {
  margin: 15px 0 15px 25px;
}

.openMenus {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 15px;
  margin-top: 30px;
}

.leftMenu {
  background-color: #387FC6;
  width: 80px;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  overflow-y: hidden;

  &::-webkit-scrollbar {
    display: none;
  }
}

.icons {
  padding-bottom: 6px;
  text-align: center;

  img {
    width: 18px;
  }
}

.listItem {
  margin-top: 5px;
  height: 80px;
}

.listItem.active {
  background: #02a7f0;
  height: 80px;
}

.logoName {
  margin: 12px 0;
  // overflow: hidden;
  display: flex;
  justify-content: center;
}

.logoImg {
  float: left;
  margin-right: 8px;
}

.logoTitle {
  line-height: 24px;
  color: #1890ff;
}

.menuLists {
  width: 200px;
  transition: 0.3s ease;
  /*width: 200px;*/
  background: #fff;
  height: 100%;
  position: absolute;
  top: 0;
  left: 80px;
  box-shadow: 3px 0px 6px 0 rgba(0, 0, 0, 0.12);
  z-index: 9;
}

.menuList {
  // margin-top: 70px;
  height: calc(var(--heightVh) - 64px);
  overflow-y: auto;
  overflow-x: hidden;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none;
  }
}

.menuList /deep/ .ant-menu:not(.ant-menu-horizontal) .ant-menu-item-selected {
  background-color: #387FC6;
  border: 1px solid #0089d0;
  color: #fff;
}

.menuList /deep/ .ant-menu-vertical .ant-menu-item::after,
.ant-menu-vertical-left .ant-menu-item::after,
.ant-menu-vertical-right .ant-menu-item::after,
.ant-menu-inline .ant-menu-item::after {
  border: none;
}

.menuList /deep/ .ant-menu-inline .ant-menu-selected::after,
.ant-menu-inline .ant-menu-item-selected::after {
  border: none;
  transform: none;
}

.menuList /deep/ .ant-menu-item-selected>a,
.ant-menu-item-selected>a:hover {
  color: #fff;
}

.tabs {
  float: left;
  color: #387FC6;
  background: rgb(255, 255, 255);
  letter-spacing: 3px;
  height: 35px;
  margin-top: 12px;
  margin-left: 15px;
  padding: 8px 25px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
}

.ant-pro-multi-tab .ant-pro-multi-tab-wrapper /deep/ .ant-tabs {
  overflow: auto;
}

.menuList /deep/ .ant-menu-inline .ant-menu-selected::after,
.ant-menu-inline .ant-menu-item-selected::after {
  transform: none;
}

/*.ant-pro-grid-content /deep/ .ant-page-header.has-breadcrumb {*/
/*padding-top: 30px;*/
/*}*/

.ant-tabs.ant-tabs-card .ant-tabs-card-bar /deep/ .ant-tabs-tab {
  margin-right: 10px;
}

.menuLists .menuList /deep/ .ant-menu.ant-menu-vertical.ant-menu-root.ant-menu-light {
  border-right: none;
}

.left-layer-retract-btn {
  width: 10px;
  height: 58px;
  position: fixed;
  top: 50%;
  left: 280px;
  z-index: 900;
  transform: translateY(-50%);
  transition: 0.3s ease;
  font-size: 16px;
  overflow: hidden;

  .anticon {
    background-color: #f7f7f7;
    position: absolute;
    top: 50%;
    margin-top: -7px;
    left: -3px;
    font-size: 14px;
  }
}

.left-menu {
  // overflow: hidden;
  display: flex;
  flex-direction: column;
  // justify-content: center;
}

.left-menu-list {
  margin: 0;
  padding: 0;
  position: relative;
  overflow-x: hidden;
  overflow-y: auto;
  height: calc(100% - 160px);
  width: 120px;
  user-select: none;

  li {
    white-space: nowrap;
    width: 80px;
    height: 58px;
    padding: 8px 24px;
    margin-bottom: 16px;
    text-align: center;
    cursor: pointer;
    opacity: 0.6;
    position: relative;

    &:nth-last-of-type(1) {
      margin-bottom: 0;
    }

    &::after {
      content: '';
      position: absolute;
      display: block;
      top: -24px;
      left: 0;
      width: 76px;
      height: 58px;
    }

    img {
      width: 18px;
      height: 18px;
      margin-bottom: 6px;
    }

    p {
      display: block;
      width: 28px;
      height: 14px;
      overflow: hidden;
      line-height: 14px;
      color: #fff;
    }
  }

  .left-menu-item-active {
    opacity: 1;
  }
}

.left-menu-list-cursor {
  width: 3px;
  height: 58px;
  background-color: #fff;
  position: absolute;
  left: 0;
}

.left-menu-btn {
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;

  i {
    font-size: 24px;
    color: #fff;
    cursor: pointer;

    &[disabled~='disabled'] {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }
}
</style>
